package com.laikan.library.httpvolley.helper;

import android.content.Context;
import com.android.volley.*;
import com.laikan.library.R;
import com.socks.library.KLog;

/**
 * 处理网络请求错误
 *
 * @author anrun
 */
public class VolleyErrorHandler {

    public VolleyError volleyError;
//    public int errorCode = geErrortMessage();
    public static int UNKONWN_ERROR = 900;
    public static int TIME_OUT_ERROR = 901;
    public static int NETWORK_ERROR = 902;
    public static int SERVER_ERROR = 903;

    public VolleyErrorHandler(VolleyError volleyError) {


        this.volleyError = volleyError;
    }

    /**
     * Returns appropriate message which is to be displayed to the user
     * against the specified error object.
     * AuthFailureError：如果在做一个HTTP的身份验证，可能会发生这个错误。
     * NetworkError：Socket关闭，服务器宕机，DNS错误都会产生这个错误。
     * NoConnectionError：和NetworkError类似，这个是客户端没有网络连接。
     * ParseError：在使用JsonObjectRequest或JsonArrayRequest时，如果接收到的JSON是畸形，会产生异常。
     * SERVERERROR：服务器的响应的一个错误，最有可能的4xx或5xx HTTP状态代码。
     * TimeoutError：Socket超时，服务器太忙或网络延迟会产生这个异常。默认情况下，Volley的超时时间为2.5秒。如果得到这个错误可以使用RetryPolicy。
     */
    public int geErrortMessage() {
//        KLog.e("volleyError getMessage: " + volleyError.getMessage()
//               + "  getLocalizedMessage: " + volleyError.getLocalizedMessage()
//               + "  getNetworkTimeMs: " + volleyError.getNetworkTimeMs());
        if (volleyError instanceof TimeoutError) {
            return TIME_OUT_ERROR;
        }else if (isNetworkProblem(volleyError)) {
            return NETWORK_ERROR;
        }else if (isServerProblem(volleyError)) {
            if (volleyError.networkResponse != null){
                return volleyError.networkResponse.statusCode;
            }else {

                return SERVER_ERROR;
            }
        }
        return UNKONWN_ERROR;
    }

    /**
     * Determines whether the error is related to network
     *
     * @param error
     *
     * @return
     */
    private boolean isNetworkProblem(Object error) {

        return (error instanceof NetworkError);
    }

    /**
     * Determines whether the error is related to server
     *
     * @param error
     *
     * @return
     */
    private boolean isServerProblem(Object error) {

        return (error instanceof ServerError) || (error instanceof AuthFailureError);
    }

    /**
     * Handles the server error, tries to determine whether to show a stock message or to
     * show a message retrieved from the server.
     *
     * @param err
     * @param context
     *
     * @return
     */
    private String handleServerError(Object err, Context context) {
        String error_msg = context.getResources().getString(R.string.common_error_generic);
        VolleyError error = (VolleyError)err;
        NetworkResponse response = error.networkResponse;
        if (response != null) {
            KLog.e("response.statusCode::" + response.statusCode);
            switch (response.statusCode) {
                case 401:
                    //auth_token 过期
                    error_msg = context.getResources().getString(R.string.error_http_401);
                    break;
                case 403:
                    //请求方式不对
                    error_msg = context.getResources().getString(R.string.common_error_unlogin);
                    break;
                case 404:
                    //请求错误(地址)
                    error_msg = context.getResources().getString(R.string.error_http_404);
                    break;
                case 408:
                    //请求错误(地址)
                    error_msg = "";
                    break;
                case 500:
                    //大于500均属于服务器错误
                    try {
                        String errMsg = new String(response.data);
                        error_msg = "SCode：" + response.statusCode + ": " + errMsg;
                        break;
                    }catch (Exception e) {
                        e.printStackTrace();
                    }
                    error_msg = context.getResources().getString(R.string.velloy_error_server) + "Scode：" + response.statusCode;
                    break;
                default:
                    error_msg = context.getResources().getString(R.string.common_error_unknown) + response.statusCode;
                    break;
            }
        }
        return error_msg;
    }

    /**
     * 禁止访问，登录失效或者未登录
     */
    public boolean isNeedLoginError() {

        boolean result = false;
        if (volleyError != null && volleyError.networkResponse != null && volleyError.networkResponse.statusCode == 403) {
            result = true;
        }
        return result;
    }
}
